using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace IceInkCapsLodkTip
{
    static class Program
    {
        private static Mutex _appMutex;
        private const string PipeName = "CapsLockIndicator_IPC_Pipe";

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

        private const int SW_RESTORE = 9;
        private const int SW_SHOW = 5;

        [STAThread]
        static void Main(string[] args)
        {
            // 步骤1: 检查是否已有实例运行
            if (IsAlreadyRunning())
            {
                // 步骤2: 发送命令给已有实例
                if (args.Length > 0)
                {
                    SendCommand(string.Join(" ", args));
                }
                else
                {
                    // 步骤3: 激活已有实例
                    ActivateExistingInstance();
                }

                // 步骤4: 退出当前实例
                return;
            }

            // 步骤5: 正常启动应用
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
       

            // 步骤7: 运行主窗体
            var mainForm = new MainForm();

            // 步骤8: 注册清理代码
            Application.ApplicationExit += (s, e) => CleanupResources();

            Application.Run(mainForm);
        }

        private static bool IsAlreadyRunning()
        {
            try
            {
                // 创建用户特定的互斥体名称
                string mutexName = $@"Global\CapsLockIndicator_{WindowsIdentity.GetCurrent().User.Value}";

                _appMutex = new Mutex(true, mutexName, out bool createdNew);
                return !createdNew;
            }
            catch
            {
                // 互斥体创建失败，使用备用方案
                return CheckByProcessName();
            }
        }

        private static bool CheckByProcessName()
        {
            int currentId = Process.GetCurrentProcess().Id;
            string processName = Path.GetFileNameWithoutExtension(
                Process.GetCurrentProcess().MainModule.FileName);

            foreach (Process p in Process.GetProcessesByName(processName))
            {
                if (p.Id != currentId)
                    return true;
            }
            return false;
        }

        private static void ActivateExistingInstance()
        {
            try
            {
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id == current.Id) continue;

                    IntPtr hWnd = process.MainWindowHandle;
                    if (hWnd == IntPtr.Zero) continue;

                    if (IsIconic(hWnd))
                    {
                        ShowWindowAsync(hWnd, SW_RESTORE);
                    }

                    SetForegroundWindow(hWnd);
                    break;
                }
            }
            catch
            {
                // 忽略错误
            }
        }

    

        private static void SendCommand(string command)
        {
            try
            {
                using (var client = new NamedPipeClientStream(
                    ".",
                    PipeName,
                    PipeDirection.Out))
                {
                    client.Connect(1000); // 1秒超时
                    byte[] bytes = Encoding.UTF8.GetBytes(command);
                    client.Write(bytes, 0, bytes.Length);
                }
            }
            catch
            {
                // 无法连接到已有实例
            }
        }

        private static void ProcessCommand(string command)
        {
            // 处理命令，例如：
            switch (command.ToLower())
            {
                case "show":
                    ActivateExistingInstance();
                    break;
                case "settings":
                    // 打开设置窗口
                    break;
                case "exit":
                    Application.Exit();
                    break;
                default:
                    // 自定义命令处理
                    break;
            }
        }

        private static void CleanupResources()
        {
            try
            {
                if (_appMutex != null)
                {
                    _appMutex.ReleaseMutex();
                    _appMutex.Close();
                    _appMutex = null;
                }
            }
            catch
            {
                // 忽略清理错误
            }
        }
    }
}